#include "SCUserDB.h"
#include <cctype>

using std::string;

// declare the static instance
// it's import, or will ld failed
UserDatabase::users UserDatabase::m_users;

UserDatabase::iterator UserDatabase::Find(const conn* p_conn){
	iterator itr;
	itr = m_users.begin();
	while( itr != m_users.end() ){

		if(itr->connection == p_conn){
			return itr;
		}
		++itr;
	}
	//no match ,return iterator of end 
	return itr;

}

bool UserDatabase::AddUser(conn* p_conn, string& p_name){
	if( !HasUser(p_name) && IsValidName(p_name) ){
		m_users.push_back( User(p_conn, p_name) );
		return true;
	}
	return false;
}

void UserDatabase::DeleteUser(const conn* p_conn){
	iterator itr = Find(p_conn);
	if( itr != m_users.end() ){
		m_users.erase(itr);
	}
}

bool UserDatabase::HasUser(const string& p_name){
	iterator itr;
	itr = m_users.begin();
	while( itr!=m_users.end() ){
		if( itr->name == p_name )  return true;
		++itr;
	}
	return false;
}

bool UserDatabase::IsValidName(const string& p_name){
	static string inv = " \"'~!@#$%^&*+/\\[]{}<>()=.,?;:";
	if( (!isalpha(p_name[0]))  ||
		(p_name.size()>16 || p_name.size()<3) ||
		(p_name.find_first_of(inv) != string::npos) )
		return false;
	return true; 
		
}